<template>
    <el-dialog v-model="visible" :title="isLogin ? '用户登录' : '用户注册'" width="400px" :close-on-click-modal="false"
        :close-on-press-escape="false" center class="login-modal">
        <!-- 登录表单 -->
        <el-form v-if="isLogin" ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="0" size="large">
            <el-form-item prop="userName">
                <el-input v-model="loginForm.userName" placeholder="请输入用户名" :prefix-icon="User" clearable />
            </el-form-item>

            <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" :prefix-icon="Lock"
                    show-password @keyup.enter="handleLogin" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleLogin" class="login-btn">
                    {{ loading ? '登录中...' : '登录' }}
                </el-button>
            </el-form-item>

            <div class="form-footer">
                <span>还没有账号？</span>
                <el-button type="text" @click="switchMode">立即注册</el-button>
            </div>
        </el-form>

        <!-- 注册表单 -->
        <el-form v-else ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="0" size="large">
            <el-form-item prop="userName">
                <el-input v-model="registerForm.userName" placeholder="请输入用户名" :prefix-icon="User" clearable />
            </el-form-item>

            <el-form-item prop="password">
                <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" :prefix-icon="Lock"
                    show-password />
            </el-form-item>

            <el-form-item prop="confirmPassword">
                <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" prefix-icon="Lock"
                    show-password />
            </el-form-item>

            <el-form-item prop="avatarUrl">
                <el-input v-model="registerForm.avatarUrl" placeholder="头像URL（可选）" prefix-icon="Picture" clearable />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleRegister" class="login-btn">
                    {{ loading ? '注册中...' : '注册' }}
                </el-button>
            </el-form-item>

            <div class="form-footer">
                <span>已有账号？</span>
                <el-button type="text" @click="switchMode">立即登录</el-button>
            </div>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { User, Lock } from '@element-plus/icons-vue'

// Props & Emits
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    defaultMode: {
        type: String,
        default: 'login', // 'login' | 'register'
        validator: value => ['login', 'register'].includes(value)
    }
})

const emit = defineEmits(['update:modelValue', 'success'])

// Stores
const userStore = useUserStore()


// 响应式数据
const visible = ref(props.modelValue)
const isLogin = ref(props.defaultMode === 'login')
const loading = ref(false)

// 表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 登录表单
const loginForm = reactive({
    userName: '',
    password: ''
})

// 注册表单
const registerForm = reactive({
    userName: '',
    password: '',
    confirmPassword: '',
    avatarUrl: ''
})

// 表单验证规则
const loginRules = {
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度为 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度为 6 到 20 个字符', trigger: 'blur' }
    ]
}

const registerRules = {
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度为 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度为 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== registerForm.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

// 监听props变化
watch(() => props.modelValue, (val) => {
    visible.value = val
})

watch(visible, (val) => {
    emit('update:modelValue', val)
    if (!val) {
        resetForms()
    }
})

// 方法
const switchMode = () => {
    isLogin.value = !isLogin.value
    resetForms()
}

const resetForms = () => {
    // 重置表单数据
    Object.assign(loginForm, {
        userName: '',
        password: ''
    })

    Object.assign(registerForm, {
        userName: '',
        password: '',
        confirmPassword: '',
        avatarUrl: ''
    })

    // 重置表单验证
    nextTick(() => {
        loginFormRef.value?.resetFields()
        registerFormRef.value?.resetFields()
    })
}

const handleLogin = async () => {
    if (!loginFormRef.value) return

    try {
        const valid = await loginFormRef.value.validate()
        if (!valid) return

        loading.value = true
        const result = await userStore.login(loginForm)

        if (result.success) {
            ElMessage.success(result.message)
            visible.value = false
            emit('success', { type: 'login', data: userStore.userInfo })
        } else {
            ElMessage.error(result.message)
        }
    } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

const handleRegister = async () => {
    if (!registerFormRef.value) return

    try {
        const valid = await registerFormRef.value.validate()
        if (!valid) return

        loading.value = true
        const result = await userStore.register(registerForm)

        if (result.success) {
            ElMessage.success(result.message + '，请登录')
            // 注册成功后切换到登录模式
            isLogin.value = true
            resetForms()
        } else {
            ElMessage.error(result.message)
        }
    } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error('注册失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 暴露方法给父组件
defineExpose({
    switchMode,
    resetForms
})
</script>

<style scoped lang="less">
.login-modal {
    .login-btn {
        width: 100%;
        margin-top: 10px;
    }

    .form-footer {
        text-align: center;
        margin-top: 20px;
        color: #666;
        font-size: 12px;
    }
}

:deep(.el-dialog__header) {
    text-align: center;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 15px;
}

:deep(.el-form-item) {
    margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
    border-radius: 6px;
}
</style>